from flask import Blueprint
from flask_restful import Api, Resource, reqparse, marshal, fields, marshal_with

from apps.models.fault_record import FaultRecord
from exts import db

record_bp = Blueprint("record", __name__)
api = Api(record_bp)

record_parser = reqparse.RequestParser()
record_parser.add_argument('phenomenon', type=str, help='必须含有现象', required=True)
record_parser.add_argument('cause', type=str, help='必须含有原因', required=True)
record_parser.add_argument('result', type=str, help='必须含有方法', required=True)
record_parser.add_argument('location', type=str, help='必须含有故障位置', required=True)
record_parser.add_argument('material', type=str, help='必须含有维修所需原料', required=True)


class RecordAPI(Resource):
    def get(self):
        args = record_parser.parse_args()
        phenomenon = args.get('phenomenon')
        cause = args.get('cause')
        result = args.get('result')
        location = args.get('location')
        material = args.get('material')
        fault_record = FaultRecord()
        fault_record.phenomenon = phenomenon
        fault_record.cause = cause
        fault_record.result = result
        fault_record.location = location
        fault_record.material = material
        db.session.add(fault_record)
        db.session.commit()
        return {"status": 200}


record_fields = {
    "date_time": fields.String,
    "phenomenon": fields.String,
    "cause": fields.String,
    "result": fields.String,
    'location': fields.String,
    'material': fields.String
}


class QueryAPI(Resource):
    @marshal_with(record_fields)
    def get(self):
        datas = FaultRecord.query.all()
        return datas


api.add_resource(RecordAPI, "/addrecord")
api.add_resource(QueryAPI, "/record")
